﻿using HandyControl.Controls;
using HandyControl.Tools.Extension;
using System;
using System.Drawing;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using AudioTransfer.ViewModels;
using MessageBox = HandyControl.Controls.MessageBox;
using Window = System.Windows.Window;
using System.Linq;
using Prism.Regions;
using AudioTransfer.ViewModels;
using Color = System.Windows.Media.Color;
using System.Windows.Media.Imaging;

namespace AudioTransfer.Views
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class HomeWindow : Window
    {
        private HomeWindowViewModel vm;
        private readonly IRegionManager _regionManager;

        public HomeWindow(IRegionManager regionManager)
        {
            InitializeComponent();
            vm = DataContext as HomeWindowViewModel;
            ClapseShow.Hide();
            _regionManager = regionManager;
        }

        private void BtMin_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }

        private void BtMax_Click(object sender, RoutedEventArgs e)
        {
            if (this.WindowState == WindowState.Maximized)
                this.WindowState = WindowState.Normal;
            else
                this.WindowState = WindowState.Maximized;
        }

        //private void BtClose_Click(object sender, RoutedEventArgs e)
        //{
        //    // 获取TPAutoUploadViewModel并注销热键
        //    var tPAutoUploadViewModel = _regionManager.Regions["ContentRegion"].ActiveViews
        //        .OfType<TPAutoUpload>()
        //        .FirstOrDefault()?.DataContext as TPAutoUploadViewModel;
            
        //    if (tPAutoUploadViewModel != null)
        //    {
        //        tPAutoUploadViewModel.UnregisterGlobalHotKey();
        //    }

        //    this.Close();
        //}

        private void NotifyIcon_Click(object sender, RoutedEventArgs e)
        {
            this.Show();
        }


        /// <summary>
        /// 只有在收缩栏关闭时才进行Tooltip
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SideMenuItem_MouseEnter(object sender, MouseEventArgs e)
        {
            var sideMenuItem = sender as SideMenuItem;
            if (vm != null)
            {
                if (vm.IsCollapsed)
                {
                    sideMenuItem.ToolTip = sideMenuItem.Header.ToString();
                }
                else sideMenuItem.ToolTip = null;
            }

        }
        /// <summary>
        /// 是否隐藏标题栏图标
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (vm != null)
            {
                if (!vm.IsCollapsed)
                {
                    ClapseShow.Show();
                    ExpandShow.Hide();
                }
                else
                {
                    ExpandShow.Show();
                    ClapseShow.Hide();
                }
            }
        }

        private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if(e.ButtonState == MouseButtonState.Pressed)
            {
                DragMove();
            }
        }

        #region Window Resize Methods
        private void ResizeTop(object sender, MouseButtonEventArgs e)
        {
            ResizeWindow(ResizeDirection.Top);
        }

        private void ResizeBottom(object sender, MouseButtonEventArgs e)
        {
            ResizeWindow(ResizeDirection.Bottom);
        }

        private void ResizeLeft(object sender, MouseButtonEventArgs e)
        {
            ResizeWindow(ResizeDirection.Left);
        }

        private void ResizeRight(object sender, MouseButtonEventArgs e)
        {
            ResizeWindow(ResizeDirection.Right);
        }

        private void ResizeTopLeft(object sender, MouseButtonEventArgs e)
        {
            ResizeWindow(ResizeDirection.TopLeft);
        }

        private void ResizeTopRight(object sender, MouseButtonEventArgs e)
        {
            ResizeWindow(ResizeDirection.TopRight);
        }

        private void ResizeBottomLeft(object sender, MouseButtonEventArgs e)
        {
            ResizeWindow(ResizeDirection.BottomLeft);
        }

        private void ResizeBottomRight(object sender, MouseButtonEventArgs e)
        {
            ResizeWindow(ResizeDirection.BottomRight);
        }

        private void ResizeWindow(ResizeDirection direction)
        {
            SendMessage(GetWindowHandle(this), WM_SYSCOMMAND, (IntPtr)(61440 + direction), IntPtr.Zero);
        }

        private IntPtr GetWindowHandle(Window window)
        {
            return new System.Windows.Interop.WindowInteropHelper(window).Handle;
        }

        private const int WM_SYSCOMMAND = 0x112;

        private enum ResizeDirection
        {
            Left = 1,
            Right = 2,
            Top = 3,
            TopLeft = 4,
            TopRight = 5,
            Bottom = 6,
            BottomLeft = 7,
            BottomRight = 8,
        }

        [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = false)]
        private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
        #endregion

        // 主题按钮：打开颜色选择对话框
        private void ThemeButton_Click(object sender, RoutedEventArgs e)
        {
            var colorDialog = new ColorDialog
            {
                Owner = this
            };
            
            if (colorDialog.ShowDialog() == true)
            {
                var mainGrid = FindMainGrid();
                if (mainGrid != null)
                {
                    if (colorDialog.IsGradient)
                    {
                        // 应用渐变色背景
                        var gradientBrush = new LinearGradientBrush(
                            new GradientStopCollection
                            {
                                new GradientStop(Colors.White, 0.0),
                                new GradientStop(colorDialog.SelectedColor, 1.0)
                            },
                            new System.Windows.Point(0, 0),
                            new System.Windows.Point(1, 1)
                        );
                        mainGrid.Background = gradientBrush;
                    }
                    else
                    {
                        // 应用纯色背景
                        var solidBrush = new SolidColorBrush(colorDialog.SelectedColor);
                        mainGrid.Background = solidBrush;
                        
                        // 同时更新渐变停止点（保持一致性）
                        BackgroundGradientStop.Color = colorDialog.SelectedColor;
                    }
                }
                
                // 更新主题颜色
                UpdateThemeColors(colorDialog.SelectedColor);
            }
        }

        private void UpdateThemeColors(Color primaryColor)
        {
            // 动态更新主题颜色
            var appResources = Application.Current.Resources;
            
            // 更新 PrimaryBrush
            var primaryBrush = new SolidColorBrush(primaryColor);
            if (appResources.Contains("PrimaryBrush"))
            {
                appResources["PrimaryBrush"] = primaryBrush;
            }
            else
            {
                appResources.Add("PrimaryBrush", primaryBrush);
            }
            
            // 更新 SecondaryBrush（稍微暗一点的版本）
            var secondaryColor = Color.FromArgb(
                primaryColor.A,
                (byte)(primaryColor.R * 0.8),
                (byte)(primaryColor.G * 0.8),
                (byte)(primaryColor.B * 0.8));
            var secondaryBrush = new SolidColorBrush(secondaryColor);
            if (appResources.Contains("SecondaryBrush"))
            {
                appResources["SecondaryBrush"] = secondaryBrush;
            }
            else
            {
                appResources.Add("SecondaryBrush", secondaryBrush);
            }
        }

        private Grid FindMainGrid()
        {
            // 递归查找主 Grid
            return FindVisualChild<Grid>(this, g => g.Name == "MainGrid" || g.Background is LinearGradientBrush);
        }

        private T FindVisualChild<T>(DependencyObject parent, Func<T, bool> predicate = null) where T : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
            {
                var child = VisualTreeHelper.GetChild(parent, i);
                if (child is T result && (predicate == null || predicate(result)))
                {
                    return result;
                }

                var childOfChild = FindVisualChild<T>(child, predicate);
                if (childOfChild != null)
                {
                    return childOfChild;
                }
            }
            return null;
        }
    }
}
